/*
 * This file is part of the Sx Framework Library.
 * 
 * Copyright (C) 2013 University of Colorado Denver
 * <min.choi@ucdenver.edu> <shane.transue@ucdenver.edu>
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy 
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 * copies of the Software, and to permit persons to whom the Software is 
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in 
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 * DEALINGS IN THE SOFTWARE.
 */
#include <SxLineParser.h>

struct Sx::File::Detail::LineParserImp {
	LineParserImp(unsigned int bufferLength) {
		this->bufferLength = bufferLength;
		this->file = nullptr;
	}

	unsigned int bufferLength;

	//--------------------------------------------------------------------------
	// Utilizes a C FILE pointer to store the internal state of the LineParser.
	//--------------------------------------------------------------------------
	FILE* file;
};

using namespace Sx::File::Detail;

Sx::File::LineParser::LineParser(unsigned int bufferLength) {
	this->imp = new LineParserImp(bufferLength);
}

Sx::File::LineParser::~LineParser() {
	if ( this->imp->file != nullptr ) this->close();
	delete this->imp;
}

bool Sx::File::LineParser::open(const String& filename) {
	this->imp->file = std::fopen(filename.toAscii().constData(), "r");

	if ( this->imp->file == nullptr ) {
		std::cout << "[LineParser:open] Error: Cannot open file: " << filename << std::endl;
		return false;
	}

	std::setvbuf(this->imp->file, 0, _IOFBF, TEXT_FILE_LINE_BUFFER_LENGTH);
	return true;
}

bool Sx::File::LineParser::hasNext() {
	if ( std::feof(this->imp->file) == 0 ) return true;
	return false;
}

Sx::String Sx::File::LineParser::nextLine() {
	char* buffer = new char[this->imp->bufferLength];
	if ( !std::fgets(buffer, this->imp->bufferLength, this->imp->file) )
		return String();
	String line(buffer);
	line.remove('\n');
	line.remove('\r');
	delete [] buffer;
	buffer = nullptr;
	return line;
}

void Sx::File::LineParser::close() {
	std::fclose(this->imp->file);
	this->imp->file = nullptr;
}
